<?php
class supplier_information_concept extends system_concept_abstract {
	
	public function init() {
		$this->setRowClass('supplier_information_row');
		$this->setModel('supplier_information_model', 'supplier');
		$this->setJoinLeftModel('common_media_model', 'supplier.logo_md5 = media.md5', 'media');
		$this->setModelCols('supplier', array('id', 'name', 'title', 'logo_md5', 'licence', 'corporation', 'website'));
		$this->setModelCols('supplier', array('is_active', 'description', 'creationtime', 'modifiedtime'));
		$this->setModelCols('media', array('md5', 'size', 'type', 'extension'));
	}

	public function save($row) {
		$row->set('name', preg_replace('/[^\w-]/is', '', $row->get('name')));
		if($row->getName() == null) {
			throw new supplier_exception("Name can not be empty.");
		}
		if($row->getTitle() == null) {
			throw new supplier_exception("Title can not be empty.");
		}
		if($row->getId()) {
			if($this->fetch(array('supplier.id != ?' => $row->getId(), 'supplier.name = ?' => $row->getName()))) {
				throw new supplier_exception("Name ({$row->getName()}) is already existing.");
			}
			$row->setModifiedtime(system_date::timestamp());
			$this->getModel('supplier')->update($row->getModelData('supplier'), array('id=?' => $row->getId()));
			return $row;
		}
		if($this->fetch(array('supplier.name = ?' => $row->getName()))) {
			throw new supplier_exception("Name ({$row->getName()}) is already existing.");
		}
		$row->setCreationtime(system_date::timestamp());
		$row->setModifiedtime(system_date::timestamp());
		$id = $this->getModel('supplier')->insert($row->getModelData('supplier'));
		$row->setId($id);
		return $row;
	}

}